#!/usr/bin/python
# -*- coding: utf-8 -*-
# AUTHOR:   yemd
# FILENAME: py_utility.py
# CREATED:  2014-01-15 10:22
# MODIFIED: 2014-02-11 18:13


import time
import datetime
import struct
from dm_py_util import *


class PY_Utility():
	def __init__(self):
		self._FMT_DATETIME = "%Y-%m-%d %H:%M:%S"
		self._FMT_DATE = "%Y-%m-%d"

	"""
	计算程序运行时间，单位微妙;
	stime为datetime.datetime类型,可由start_time()获取
	etime为datetime.datetime类型,可由end_time()获取
	"""
	def process_time(self,etime,stime):
		return (etime-stime).seconds*1000000 + (etime-stime).microseconds
			
	def start_time(self):
		return datetime.datetime.now()

	def end_time(self):
		return datetime.datetime.now()
	

	"""
	时间戳和时间串相互转化相关
	时间戳可由time.time()获取
	时间串的固定格式: 2014-02-11 10:00:00
	"""
	def time_to_str(self,timestamp):
		return time.strftime(self._FMT_DATETIME,time.localtime(timestamp))
	def str_to_time(self,timestr):
		return time.mktime(time.strptime(timestr,self._FMT_DATETIME))

	def time_to_date(self,timestamp):
		return time.strftime(self._FMT_DATE,time.localtime(timestamp))
	def date_to_time(self,timestr):
		return time.mktime(time.strptime(timestr,self._FMT_DATE))


	"""
	1、整型转为字节型字符串
	2、字节型字符串转为整型
	"""
	def uint32_to_bstr(self,val):
		if not isinstance(val,int):
			return ""
		return struct.pack('I',val)

	def bstr_to_uint32(self,bstr):
		if not isinstance(bstr,str):
			return 0
		(back,) = struct.unpack('I',bstr)
		return back


	"""
	将格式化protobuf压缩成一行输出	
	"""
	def fast_writer(self,str_proto):
		return str_proto.replace('  ','').replace(' ','').replace('{\n','{').\
				replace('\n}\n','}, ').replace('\n',', ')


	"""
	是否字符串类型
	"""
	def is_str(self,s):
		if not isinstance(s,str):
			raise DM_InputError('not str')



if __name__ == '__main__':
	
	u = PY_Utility()

	s = u.start_time()

	print 'time-to-str ',u.time_to_str(1392172677.073298)	
	
	print 'str-to-time ',u.str_to_time('2014-02-12 10:37:57')

	e = u.end_time()

	print 'process_time ',u.process_time(e,s)

